package com.begye.smartloan.apptest.huankuan

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtPinHuanKuanProcessBinding
import com.begye.smartloan.apptest.ext.addUnderLine
import com.begye.smartloan.apptest.ext.toThousandUnitFormat
import com.begye.smartloan.apptest.fangkuanzhong.FangKuanZhongActivity
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.homeadsource.HomeAdSourceActivity
import com.begye.smartloan.apptest.jujue.JuJueActivity
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.renzheng.RenZhengActivity
import com.begye.smartloan.apptest.renzheng.bangka.RenZhengBangKaActivity
import com.begye.smartloan.apptest.renzheng.document.RenZhengDocumentActivity
import com.begye.smartloan.apptest.renzheng.lianxiren.RenZhengLianXiRenActivity
import com.begye.smartloan.apptest.renzheng.selfie.RenZhengSelfieActivity
import com.begye.smartloan.apptest.shenhezhong.ShenHeZhongActivity
import com.begye.smartloan.apptest.tool.PageTagTool
import com.begye.smartloan.apptest.tool.addTouch
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.openSystemBrowser
import com.util.utillib.extend.toNextActivity
import java.util.Timer
import java.util.TimerTask

@SuppressLint("CustomSplashScreen")
class PinHuanKuanProcessingActivity : AppCompatActivity() {

    private lateinit var _binding: AtPinHuanKuanProcessBinding
    private var _pinTimer = Timer()

    private val _huanKuanViewModel by lazy {
        ViewModelProvider(this)[HuanKuanViewModel::class.java]
    }

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        _binding = AtPinHuanKuanProcessBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
        configUIData()
    }

    private fun configYongHuLiuChengState() {

        _huanKuanViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onHasOrderStatusLiveData.observe(this) {
            it?.let { result ->
                when (result) {
                    PageTagTool.dai_huan_kuan -> {
                        toNextActivity(
                            activity = HuanKuanActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.fang_kuan_zhong -> {
                        toNextActivity(
                            activity = FangKuanZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.shen_he_zhone -> {
                        toNextActivity(
                            activity = ShenHeZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.ju_jue -> {
                        toNextActivity(
                            activity = JuJueActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }
                }
            }
        }

        _yongHuLiuChengViewModel.onDoingRenZhengPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingLianXiRenPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengLianXiRenActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingBangKaFrPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengBangKaActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingDocumentPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengDocumentActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingSelfiePageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengSelfieActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onAllDoneLiveData.observe(this) {
            if (it.isNotBlank()) {
                // to shen qing ye
                toNextActivity(
                    activity = HomeAdSourceActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun configUIState() {

        _huanKuanViewModel.onPinStatusLiveData.observe(this) {
            it?.let { result ->
                try {
                    val product = result.optString("product", "")
                    val jinE = result.optString("amount", "").toThousandUnitFormat()
                    val jinEReceived =
                        result.optString("realRepayAmount", "").toThousandUnitFormat()
                    val status = result.optString("status", "")
                    val pid = result.optString("transactionId", "")
                    val pTime = result.optString("realRepayTime", "")
                    val createTime = result.optString("createTime", "")
                    val failedTime = result.optString("failedTime", "")
                    val failReason = result.optString("failReason", "")

                    _binding.atPinHuanKuanProcessJinEValue.text = jinE
                    _binding.atPinHuanKuanProcessProductValue.text = product

                    if (status.contains("SUCC", true)) {
                        setCutDownFinished()
                        // to success page
                        val params = HashMap<String, String>().apply {
                            put("product", product)
                            put("jinE", jinE)
                            put("jinEReceived", jinEReceived)
                            put("pid", pid)
                            put("pTime", pTime)
                        }
                        toNextActivity(
                            activity = PinHuanKuanSuccessActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP,
                            params = params
                        )

                    } else if (status.contains("FAIL", true)) {
                        setCutDownFinished()
                        // to fail page
                        val params = HashMap<String, String>().apply {
                            put("product", product)
                            put("jinE", jinE)
                            put("jinEReceived", jinEReceived)
                            put("pid", pid)
                            put("createTime", createTime)
                            put("failedTime", failedTime)
                            put("failReason", failReason)
                        }
                        toNextActivity(
                            activity = PinHuanKuanFailedActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP,
                            params = params
                        )
                    }
                } catch (e: Exception) {
                    //
                }
            }
        }

        _huanKuanViewModel.onHuanKuanUrlLiveData.observe(this) {
            it?.let { result ->
                val isPin = result.optBoolean("isPin", false)
                if (isPin) {
                    setCutDownStart()
                    _huanKuanViewModel.requestPinStatus()
                } else {
                    _binding.atPinHuanKuanProcessMakeAgain.isEnabled = true
                    val targetUrl = result.optString("targetUrl", "")
                    if (targetUrl.isNotBlank()) {
                        openSystemBrowser(targetUrl)
                    }
                }
            }
        }
    }

    private fun configUIEvent() {

        _binding.atPinHuanKuanProcessNar.initConfig(
            text = getString(R.string.huan_kuan_text_35),
            textColor = "#000000",
            leftResId = R.drawable.dres_39,
            rightResId = R.drawable.dres_38
        ) {
            if (0 == it) {
                toNextActivity(
                    activity = HuanKuanActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }

        _binding.atPinHuanKuanProcessRefresh.addUnderLine()

        _binding.atPinHuanKuanProcessRefresh.setOnClickListener {
            val thirdOrderId = _huanKuanViewModel.pinThirdOrderId
            if (thirdOrderId.isBlank()) {
                finish()
                return@setOnClickListener
            }
            _huanKuanViewModel.requestPinStatus()

            //
            addTouch(type = "pin_huan_kuan_processing_refresh_click")
        }

        _binding.atPinHuanKuanProcessMakeAgain.setOnClickListener {
            val curText =
                _binding.atPinHuanKuanProcessMakeAgain.text.toString().trim()
            if (curText.contains("(") or curText.contains(")")) {
                return@setOnClickListener
            }

            _binding.atPinHuanKuanProcessMakeAgain.isEnabled = false
            _huanKuanViewModel.requestHuanKuanUrl()

            //
            addTouch(type = "pin_huan_kuan_processing_try_again_click")
        }
    }

    private fun configUIData() {
        val orderId = intent.getStringExtra("orderId") ?: ""
        val thirdOrderId = intent.getStringExtra("thirdOrderId") ?: ""
        _huanKuanViewModel.pinOrderId = orderId
        _huanKuanViewModel.pinThirdOrderId = thirdOrderId

        if (thirdOrderId.isBlank()) {
            finish()
            return
        }

        setCutDownStart()

        _huanKuanViewModel.requestPinStatus()
    }

    @SuppressLint("SetTextI18n")
    private fun setCutDownFinished() {
        try {
            _pinTimer.cancel()

            _pinTimer.cancel()
            _binding.atPinHuanKuanProcessMakeAgain.setBackgroundResource(
                R.drawable.layer_c25_000000
            )
            _binding.atPinHuanKuanProcessMakeAgain.text = getString(R.string.huan_kuan_text_7)
            _binding.atPinHuanKuanProcessMakeAgain.isEnabled = true

        } catch (e: Exception) {
            //
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setCutDownStart() {
        var curTick = 60
        try {
            _pinTimer.cancel()
            _pinTimer = Timer()
            _pinTimer.schedule(object : TimerTask() {
                override fun run() {
                    runOnUiThread {
                        _binding.atPinHuanKuanProcessMakeAgain.isEnabled = false
                        _binding.atPinHuanKuanProcessMakeAgain.text =
                            getString(R.string.huan_kuan_text_7) + " (${curTick}s)"
                        _binding.atPinHuanKuanProcessMakeAgain.setTextColor(Color.parseColor("#ffffff"))
                        _binding.atPinHuanKuanProcessMakeAgain.setBackgroundResource(R.drawable.layer_c25_cfcdd2)

                        if (curTick == 0) {
                            _pinTimer.cancel()
                            _binding.atPinHuanKuanProcessMakeAgain.setBackgroundResource(
                                R.drawable.layer_c25_000000
                            )

                            _binding.atPinHuanKuanProcessMakeAgain.setTextColor(Color.parseColor("#BEFF6A"))
                            _binding.atPinHuanKuanProcessMakeAgain.text =
                                getString(R.string.huan_kuan_text_7)
                            _binding.atPinHuanKuanProcessMakeAgain.isEnabled = true
                        }

                        if (curTick == 30) {
                            // 查询状态
                            if ( _huanKuanViewModel.pinThirdOrderId.isNotBlank()) {
                                _huanKuanViewModel.requestPinStatus()
                            }
                        }

                        curTick -= 1
                    }
                }
            }, 0, 1000)
        } catch (e: Exception) {
            //
        }
    }

    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}